#include "modifynamewidget.h"
#include "ui_modifynamewidget.h"

#include "modifynamethread.h"

#include <QDir>
#include <QFileDialog>
#include <QSettings>
#include <QtConcurrent>

#define OPEN_SRC_DIR_PATH "OPENSRCDIRPATH"
#define OPEN_DEST_DIR_PATH "OPENDESTDIRPATH"

ModifyNameWidget::ModifyNameWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ModifyNameWidget)
{
    ui->setupUi(this);
}

ModifyNameWidget::~ModifyNameWidget()
{
    delete ui;
}

void ModifyNameWidget::onResultReady(bool ok, const QString &msg)
{
    int val = ui->progressBar->value()+1;
    ui->progressBar->setValue(val);
    ui->startBtn->setEnabled(val == ui->progressBar->maximum());
    ui->textBrowser->append((ok?tr("OK: "):tr("FAIL: ")) + msg);
}

void ModifyNameWidget::on_startBtn_clicked()
{
    QStringList ds;
    QStringList fs;
    ui->textBrowser->clear();
    ui->startBtn->setEnabled(false);
    ui->progressBar->setValue(0);
    ds += ui->srcDirEdit->text();
    while (!ds.isEmpty()) {
        QString d = ds.takeFirst();
        QDir dir(d);
        QStringList es = dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot);
        foreach (const QString &e, es) {
            ds += dir.absoluteFilePath(e);
        }
        es = dir.entryList(QDir::Files);
        foreach (const QString &e, es) {
            fs += dir.absoluteFilePath(e);
        }
    }

    int total = fs.size();
    if (total == 0) ui->startBtn->setEnabled(true);
    ui->progressBar->setMaximum(total);
    ui->progressBar->setValue(0);

    ModifyNameThread *t = new ModifyNameThread(fs, ui->srcDirEdit->text(), ui->destDirEdit->text());
    connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
    connect(t, SIGNAL(resultReady(bool,QString)), this, SLOT(onResultReady(bool,QString)));
    t->start();
}

void ModifyNameWidget::on_srcSelBtn_clicked()
{
    QSettings s;
    QString p = s.value(OPEN_SRC_DIR_PATH).toString();
    p = QFileDialog::getExistingDirectory(this, tr("Open Src Dicom Folder"), p);
    if (!p.isEmpty()) {
        s.setValue(OPEN_SRC_DIR_PATH, p);
        ui->srcDirEdit->setText(p);
    }
}

void ModifyNameWidget::on_destSelBtn_clicked()
{
    QSettings s;
    QString p = s.value(OPEN_DEST_DIR_PATH).toString();
    p = QFileDialog::getExistingDirectory(this, tr("Open Dest Dicom Folder"), p);
    if (!p.isEmpty()) {
        s.setValue(OPEN_DEST_DIR_PATH, p);
        ui->destDirEdit->setText(p);
    }
}
